#include "IniFile.h"
#include <Windows.h>
#include <shlwapi.h>
#include "Buffer.h"



namespace Zaf {



IniFile::IniFile(const std::wstring& path) : m_path(path) {

	if (PathIsRoot(path.c_str()) == FALSE) {

		wchar_t pathBuffer[MAX_PATH];
		GetFullPathName(
			path.c_str(), 
			sizeof(pathBuffer) / sizeof(wchar_t), 
			pathBuffer, 
			nullptr
		);

		m_path = pathBuffer;
	}
}




int IniFile::ReadInt(const wchar_t* section, const wchar_t* key) const {

	return GetPrivateProfileInt(section, key, 0, m_path.c_str());
}



std::wstring IniFile::ReadString(const wchar_t* section, const wchar_t* key) const {

	Buffer<wchar_t> buffer(32);
	int readLen;

	while (true) {

		readLen = GetPrivateProfileString(
			section,
			key,
			L"",
			buffer,
			buffer.GetLength(),
			m_path.c_str()
		);

		if (readLen != buffer.GetLength() - 1) {
			break;
		}

		buffer.Resize(buffer.GetLength() * 2);
	}

	return buffer.Get();
}



void IniFile::WriteInt(const wchar_t* section, const wchar_t* key, int value) {

	WriteString(section, key, std::to_wstring((long long)value));
}



void IniFile::WriteString(const wchar_t* section, const wchar_t* key, const std::wstring& value) {

	WritePrivateProfileString(section, key, value.c_str(), m_path.c_str());
}


}